const router = require('koa-router')()
const fs = require("fs");
const path = require("path");
const uploadDir = path.join(__dirname, '../images/goods');

router.prefix('/buy')

//合并buy buydesc两个表的信息
//页面初始化时获取数据库内buy buydesc表的数据条目
router.post('/getbuybuydescbackend', async (ctx, next) => {
  let result3 = await ctx.db.EXCUTE("SET @@group_concat_max_len = 102400000000")
  let result1 = await ctx.db.EXCUTE("SELECT n.*, (SELECT GROUP_CONCAT(descimg SEPARATOR '><') FROM buydesc ni WHERE n.commodityid=ni.commodityid) AS comings FROM buy n")

  for (let i = 0; i < result1.length; i++) {
    result1[i].comimgs = (result1[i].comings || '').split('><');
    // console.log(result1[i].comings);
    //console.log(typeof (result1[i].comings));
  }

  // console.log(result1[0]);
  ctx.body = {
    code: 200,
    data: result1
  }
})
function filterArr(arr1, arr2) {
  var uid1 = []
  var uid2 = []
  for (var i in arr1) {
    uid1.push('http://localhost:8080' + arr1[i].descimg)
  }
  for (var i in arr2) {
    uid2.push(arr2[i].url)
  }
  const arr = [...uid1, ...uid2];
  // console.log(66666666666);
  // console.log(uid1);
  // console.log(55555555);
  // console.log(uid2);
  // console.log(44444);
  const newArr = arr.filter(item => {
    console.log();
    if (uid2.includes(item)) {
      console.log(1);
      return false
    } else {
      console.log(2, item);
      return true
    }
  });

  return newArr;
}
//编辑buy 有图片上传
router.post('/modifybuy', async (ctx, next) => {
  let commodityid = ctx.request.body.commodityid;
  let com_name = ctx.request.body.com_name;
  let com_place = ctx.request.body.com_place;
  let com_price = ctx.request.body.com_price;
  let com_from = ctx.request.body.com_from;
  let express_fee = ctx.request.body.express_fee;
  let com_time = ctx.request.body.com_time;
  let descid = ctx.request.body.descid;
  let descimg = ctx.request.body.descimg;
  //console.log(typeof (com_price));

  let sql0 = 'update buy set com_name=?, com_place=?, com_price=?, com_from=?, express_fee=?, com_time=? where commodityid=?'
  await ctx.db.EXCUTE(sql0, [com_name, com_place, com_price, com_from, express_fee, com_time, commodityid]);
  console.log(descimg);
  // 判断，原来图片列表descimglist中有图片被删除，删掉本地存储到图片和数据库中的数据
  let descimglist = await ctx.db.EXCUTE("select descimg from buydesc where commodityid=?", [commodityid]);
  console.log(descimglist);
  let diff = filterArr(descimglist, descimg)
  // console.log(1111111);
  // console.log(diff);
  // console.log(222222222);
  for (let i = 0; i < diff.length; i++) {
    let n = diff[i].split('http://localhost:8080')[1]
    fs.unlink(path.join(__dirname, '../' + n), async function (err) {
      if (err) {
        console.log(err);
        ctx.body = {
          code: 400
        }
      }
      await ctx.db.EXCUTE("update buy set first_img='' where commodityid=?", [commodityid]);
      await ctx.db.EXCUTE("delete from buydesc where descimg=?", [n]);
    })
  }

  let files = ctx.request.body.descimg
  for (let i = 0; i < ctx.request.body.descimg.length; i++) {
    if (!descimg[i].url.includes("http://localhost:8080")) {
      var base64Data = files[i].url.replace(/^data:image\/\w+;base64,/, "");
      var dataBuffer = Buffer.from(base64Data, 'base64');
      let imgUrl = uploadDir + '\\' + files[i].name
      fs.writeFileSync(imgUrl, dataBuffer)
      let sql1 = 'INSERT INTO buydesc (descimg,commodityid) VALUES (?,?)'

      if (i == 0) {
        console.log(0);
        console.log(commodityid);
        console.log('/images/goods/' + files[i].name);
      }
      await ctx.db.EXCUTE(sql1, ['/images/goods/' + files[i].name, commodityid])
    } else {
      // let n = descimg[0].url.split('http://localhost:8080')[1]
      if (i == 0) {
        console.log(112);
        console.log(commodityid);
        let n = descimg[i].url.split('http://localhost:8080')[1]
        console.log(n);
        await ctx.db.EXCUTE('update buy set first_img = ? where commodityid=?', [n, commodityid])
      }
      // await ctx.db.EXCUTE('update buy set first_img = ? where commodityid=?', [n, commodityid])
    }
  }
  let descarr = await ctx.db.EXCUTE('select * from buydesc where commodityid=?', [commodityid])
  await ctx.db.EXCUTE('update buy set first_img = ? where commodityid=?', [descarr[0].descimg, commodityid])
  // console.log(result1);
  ctx.body = {
    code: 200
  }

});



//编辑item 首先获取该项的内容
router.post('/getsingle', async (ctx, next) => {
  let commodityid = ctx.request.body.commodityid;

  let sql1 = 'SELECT * FROM buy WHERE commodityid=?';

  let results = await ctx.db.EXCUTE(sql1, [commodityid]);
  ctx.body = {
    code: 200,
    data: results
  };

})

// 上传前进行合法性判断
// router.post('/upload', async (ctx, next) => {
//   console.log(ctx.req.headers);
//   // console.log(ctx.request.body.file);
//   let token = ctx.req.headers.authorization
//   let localToken = ctx.request.body.token;
//   let files = ctx.request.body.files;
//   console.log(files);
//   // console.log();
//   // 解密
//   let result = jwt.verify(token, myKey)
//   for (let i = 0; i < jsonUser.length; i++) {
//     if (result.username == jsonUser[i].username) {  //判断token的有效性
//       ctx.body = {
//         code: 200,
//         msg: 'token有效',
//         state: true
//       }
//       return
//     }
//   }
//   ctx.body = {
//     msg: 'token无效',
//     state: false
//   }


// })
//增加项  上传商品图片功能在这里
router.post('/additem', async (ctx, next) => {
  let com_name = ctx.request.body.com_name;
  let com_place = ctx.request.body.com_place;
  let com_price = ctx.request.body.com_price;
  let com_from = ctx.request.body.com_from;
  let express_fee = ctx.request.body.express_fee;
  let com_time = ctx.request.body.com_time;
  let descimg = ctx.request.body.descimg;

  // console.log(ctx.request.body);
  let sql0 = 'INSERT INTO buy (com_name,com_place,com_price,com_from,express_fee,com_time) VALUES (?,?,?,?,?,?)'
  await ctx.db.EXCUTE(sql0, [com_name, com_place, com_price, com_from, express_fee, com_time]);


  //查找新更新的一行的commodityid
  let sql = 'SELECT commodityid FROM buy WHERE com_name=? AND com_place=? AND com_price=? AND com_from=? AND express_fee=? AND com_time=?'
  let commodityidarr = await ctx.db.EXCUTE(sql, [com_name, com_place, com_price, com_from, express_fee, com_time]);
  let commodityid = commodityidarr[commodityidarr.length - 1].commodityid

  let files = ctx.request.body.descimg
  // let itemUrl = ctx.request.body.itemUrl
  let imgList = []
  // console.log(files);
  for (let i = 0; i < ctx.request.body.descimg.length; i++) {
    // console.log(files[i].url);
    var base64Data = files[i].url.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = Buffer.from(base64Data, 'base64');
    let imgUrl = uploadDir + '\\' + files[i].name
    fs.writeFileSync(imgUrl, dataBuffer)
    let sql1 = 'INSERT INTO buydesc (descimg,commodityid) VALUES (?,?)'
    await ctx.db.EXCUTE(sql1, ['/images/goods/' + files[i].name, commodityid])
    if (i == 0) {
      console.log(i);
      await ctx.db.EXCUTE('update buy set first_img = ? where commodityid=?', ['/images/goods/' + files[i].name, commodityid])
    }
  }
  ctx.body = {
    code: 200
  }

});
//additem without pics
router.post('/additemnoimg', async (ctx, next) => {
  let com_name = ctx.request.body.com_name;
  let com_place = ctx.request.body.com_place;
  let com_price = ctx.request.body.com_price;
  let com_from = ctx.request.body.com_from;
  let express_fee = ctx.request.body.express_fee;
  let com_time = ctx.request.body.com_time;

  let sql0 = 'INSERT INTO buy (com_name,com_place,com_price,com_from,express_fee,com_time) VALUES (?,?,?,?,?,?)'
  await ctx.db.EXCUTE(sql0, [com_name, com_place, com_price, com_from, express_fee, com_time]);

  await ctx.db.EXCUTE("SET @@group_concat_max_len = 102400000000")
  let result1 = await ctx.db.EXCUTE("SELECT n.*, (SELECT GROUP_CONCAT(descimg SEPARATOR '><') FROM buydesc ni WHERE n.commodityid=ni.commodityid) AS comings FROM buy n")

  for (let i = 0; i < result1.length; i++) {
    result1[i].comings = (result1[i].comings || '').split('><');
    // console.log(result1[i].comings);
    //console.log(typeof (result1[i].comings));
  }

  // console.log(result1[0]);
  ctx.body = {
    code: 200,
    data: result1
  }

});
// 删除数据
router.post('/delbuybackend', async (ctx, next) => {
  let commodityid = ctx.request.body.commodityid;
  let first_img = ctx.request.body.first_img;
  let allcomimgs = ctx.request.body.comimgs
  console.log(ctx.request.body);
  console.log(allcomimgs);
  //在数据库中删除对应数据
  console.log();
  for (let i = 0; i < allcomimgs.length; i++) {
    let m = allcomimgs[i].replace('/http://localhost:8080/', '')
    let n = allcomimgs[i].split('http://localhost:8080/')[1]
    console.log(m);
    console.log(n);
    fs.unlink(path.join(__dirname, '../' + n), async function (err) {
      if (err) {
        console.log(err);
        ctx.body = {
          code: 400
        }
      }
      await ctx.db.EXCUTE(`DELETE FROM buy WHERE commodityid=${commodityid}`)
      ctx.body = {
        code: 200,
        // data: result1
      }
    })
    console.log(i);
    ctx.body = {
      code: 200
    }
  }

  // //获取删除后的全部数据
  // await ctx.db.EXCUTE("SET @@group_concat_max_len = 102400000000")
  // let result1 = await ctx.db.EXCUTE("SELECT n.*, (SELECT GROUP_CONCAT(descimg SEPARATOR '><') FROM buydesc ni WHERE n.commodityid=ni.commodityid) AS comings FROM buy n")

  // for (let i = 0; i < result1.length; i++) {
  //   result1[i].comings = (result1[i].comings || '').split('><');
  //   // console.log(result1[i].comings);
  //   //console.log(typeof (result1[i].comings));
  // }

  // console.log(result1[0]);

})


//buydesc
//页面初始化时获取数据库内buydesc表的数据条目
router.post('/getbuydesc', async (ctx, next) => {
  let sql0 = 'SELECT * FROM buydesc'
  let result = await ctx.db.EXCUTE(sql0);

  ctx.body = {
    code: 200,
    data: result
  };
})

//编辑
router.post('/uploadimg', async (ctx, next) => {
  let commodityid = ctx.request.body.commodityid;
  let descid = ctx.request.body.descid;
  let descimg = ctx.request.body.descimg;

  let sql1 = 'UPDATE buydesc SET descimg=? WHERE commodityid=? AND descid=?'
  await ctx.db.EXCUTE(sql1, [descimg, commodityid, descid])

  let sql2 = 'SELECT * FROM buydesc ORDER BY commodityid'
  let result = await ctx.db.EXCUTE(sql2);

  ctx.body = {
    code: 200,
    data: result
  };

});

//编辑item 首先获取该项的内容
router.post('/getsinglebuydesc', async (ctx, next) => {
  let commodityid = ctx.request.body.commodityid;

  let sql0 = 'SELECT * FROM buydesc WHERE commodityid=?'
  let result = await ctx.db.EXCUTE(sql0, [commodityid]);

  ctx.body = {
    code: 200,
    data: result
  };
})






router.post('/getgoods', async (ctx, next) => {
  let data = ctx.request.body;
  let page = data.page;
  let size = data.size;
  console.log(data);
  let result = await ctx.db.EXCUTE("select * from buy limit ?, ?", [(page - 1) * size, size]);
  console.log(111111);
  console.log(result);
  // let result = await ctx.db.EXCUTE('select * from buy order by commodityid');
  // let result3 = await ctx.db.EXCUTE("SET @@group_concat_max_len = 1024000000")
  // // let result = await ctx.db.EXCUTE("SELECT n.*, (SELECT GROUP_CONCAT(descimg SEPARATOR '  ') FROM buydesc ni WHERE n.commodityid=ni.commodityid) AS comimgs FROM buy n")
  // let result = await ctx.db.EXCUTE("select * from buy ");
  // for (let i = 0; i < result.length; i++) {
  //   let r = await ctx.db.EXCUTE("select descimg from buydesc where commodityid=?", [result[i].commodityid]);
  //   result[i].comimgs = r[0].descimg
  // }

  // console.log(123456);
  // for(let i=0; i<result.length; i++){
  //   let r = result[i].comimgs.split('  ');
  //   result[i].comimgs = r[0]
  //   }
  // console.log(result);
  ctx.body = {
    code: 200,
    data: result
  }
})
router.post('/getdetail', async (ctx, next) => {
  let commodityid = ctx.request.body.commodityid
  let result0 = await ctx.db.EXCUTE('SELECT * FROM buy where commodityid=?', [commodityid]);
  let result = await ctx.db.EXCUTE('SELECT descimg FROM buydesc where commodityid=? order by descid', [commodityid]);
  console.log(result);
  ctx.body = {
    code: 200,
    data: result0,
    imgs: result
  }
})
router.post('/searchgoods', async (ctx, next) => {
  let text = ctx.request.body.text
  let result = await ctx.db.EXCUTE("SELECT * FROM buy WHERE com_name LIKE '%" + text + "%'");
  if (result) {
    for (let i = 0; i < result.length; i++) {
      let r = await ctx.db.EXCUTE("select descimg from buydesc where commodityid=?", [result[i].commodityid]);
      result[i].comimgs = r[0].descimg
    }
  }
  console.log(result);
  ctx.body = {
    code: 200,
    data: result
  }
})
module.exports = router
